/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2025-2025. All rights reserved.
 *
 */

import path from 'path';

import { cloneDeep } from '@baize/wdk';
import { FileSet, TaskInputValue } from '@ohos/hvigor';
import * as fse from 'fs-extra';

import { findTargetProduct } from '../common/find-target-product.js';
import { projectOhosConfigManager } from '../common/global/project-ohos-config-manager.js';
import { BuildArtifactConst } from '../const/build-directory-const.js';
import { ProjectModelImpl } from '../model/project/project-model-impl.js';
import { TargetSourceSetModel } from '../model/source-set/source-set-model.js';
import { AppOpt } from '../options/build/app-ohos-config.js';
import { AppJson } from '../options/configure/app-json-options.js';
import { ModuleJson } from '../options/configure/module-json-options.js';
import { OhosLogger } from '../utils/log/ohos-logger.js';
import { checkAppPreloadHintStartupTasksSrcEntry } from '../utils/task-util.js';
import { validatePackageBySystemHspModel } from '../utils/validate/validate-systemHsp.js';
import { BasePackHapTask } from './base/base-pack-hap-task.js';
import { TaskNames } from './common/task-names.js';
import { TargetTaskService } from './service/target-task-service.js';

import Task = TaskNames.Task;
import AppOptObj = AppJson.AppOptObj;
import ModuleOptObj = ModuleJson.ModuleOptObj;

/**
 * Fast packaging hap task
 *
 * @since 2025/2/27
 */
export class FastPackageHap extends BasePackHapTask {
  // target相关属性
  private readonly appOptObj: AppOptObj;
  private readonly targetModuleOptObj: ModuleOptObj;
  private readonly targetJsonPath: string;

  constructor(taskService: TargetTaskService) {
    super(taskService, Task.FAST_PACKAGE, 'hap', OhosLogger.getLogger(FastPackageHap.name));
    const targetSourceSetModel: TargetSourceSetModel = taskService.getTargetData().getModuleSourceSetModel() as TargetSourceSetModel;
    const targetRes = targetSourceSetModel.getModuleTargetRes();
    this.targetModuleOptObj = targetRes.getModuleJsonOpt();
    this.targetJsonPath = targetRes.getJsonPath();
    const appRes = (this.projectModel as ProjectModelImpl).getAppRes();
    this.appOptObj = appRes.getAppResOpt();
  }

  declareInputs(): Map<string, TaskInputValue> {
    const map = super.declareInputs();
    const appOptFromConfig: AppOpt = cloneDeep(projectOhosConfigManager.getOverrides()?.appOpt);
    map.set('bundleType', appOptFromConfig?.bundleType ?? findTargetProduct(this.projectModel).bundleType ?? this.projectModel.getBundleType());
    return map;
  }

  declareInputFiles(): FileSet {
    const fileSet = super.declareInputFiles();
    if (fse.existsSync(this.intermediateTempStartupFilePath)) {
      fileSet.addEntry(this.intermediateTempStartupFilePath);
    }
    return fileSet;
  }

  async beforeAlwaysAction(): Promise<void> {
    await super.beforeAlwaysAction();
  }

  protected async doTaskAction(): Promise<void> {
    // 检查启动框架配置文件中appPreloadHintStartupTasks srcEntry配置的so在libs下存在
    const baseNativeLibsPath = path.resolve(this.pathInfo.getIntermediatesPatch(), BuildArtifactConst.BASE_NATIVE_LIBS_JSON);
    checkAppPreloadHintStartupTasksSrcEntry(this.intermediateTempStartupFilePath, baseNativeLibsPath, this._log, this.moduleName);
    // 系统级hsp校验 不支持打包hap包
    validatePackageBySystemHspModel(this.service, this.appOptObj, this.targetJsonPath, this.targetModuleOptObj);

    return this.copyIntermediates();
  }
}
